# coding: utf8
'''
用户登录
@author zhuxuezheng@gmail.com
'''
__revision__ = '0.1'

import hashlib
import web
from forms import login_form
from models import User
from SakyaTemplate import lookup

class Login:
    def GET(self):
        form = login_form()
        if form.username == None:
            form.username = web.ctx.session.get('logId')
        return lookup.get_template('user/login.htm').render(form = form)

class DoLogin:
    def POST(self):
        form = login_form()
        if not form.validates():
            return lookup.get_template('user/login.htm').render(form = form)
        i_username = form.username.value
        i_password = hashlib.md5(form.password.value).hexdigest()
        user = web.ctx.orm.query(User).filter_by(username = i_username, password = i_password).first()
        if user:
            web.ctx.session.isAuth = True
            web.ctx.session.uid = user.id
            web.ctx.session.logId = i_username
            raise web.seeother('../index.htm') 
        else:
            web.ctx.session.isAuth = False
            return lookup.get_template('user/login.htm').render(form = form, msg ='用户名或密码错误！')
        #raise web.seeother("/") /user/
        #web.redirect("/123")
        #return render_index.test()

class LoginOut:
    def GET(self):
        web.ctx.session.isAuth = False
        web.ctx.session.kill()
        return web.seeother('../index.htm')

